package com.web.exiaodao.remote.service.impl;

import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.LotteryRule;
import com.web.exiaodao.business.entity.MakeMoneyTable;
import com.web.exiaodao.remote.service.*;
import com.web.exiaodao.remote.vo.ConfigurationTableVo;
import com.web.exiaodao.remote.vo.LotteryRuleVo;
import java.util.List;
import java.util.Map;

import com.web.exiaodao.remote.vo.UserVo;
import com.web.webstart.base.util.Identities;
import com.web.webstart.base.util.jpa.WebUitl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.repository.LotteryRuleRepository;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;

/**
 * @author: zhangl
 * @times: 2015-5-15下午06:46:35
 * 类的说明：前端APILotteryRule接口实现类
 **/
@Service("ApiLotteryRuleService")
@Transactional(readOnly = false)
public class ApiLotteryRuleServiceImpl extends BaseService<LotteryRule> implements ApiLotteryRuleService{

	private static final Logger LOGGER = Logger.getLogger(ApiLotteryRuleServiceImpl.class);

	@Autowired
	private ApiUserService userService;

	@Autowired
	LotteryRuleRepository lotteryRuleRepository;

	@Autowired
	private ApiConfigurationTableService configurationTableService;

	@Autowired
	private ApiMakeMoneyTableService makeMoneyTableService;


	@Override
	public XaResult<LotteryRuleVo> findOne(Long tId) throws BusinessException {
		LotteryRule obj = lotteryRuleRepository.findByIdAndStatusNot(tId,XaConstant.Status.delete);
		XaResult<LotteryRuleVo> xr = new XaResult<LotteryRuleVo>();
		if (XaUtil.isNotEmpty(obj)) {
			if(obj.getMoney() == 0){
				xr.setObject(JSON.parseObject(JSON.toJSONString(obj),LotteryRuleVo.class));
				xr.getObject().setId(obj.getId());
			}else{
				obj.setMemo("中奖");
				xr.setObject(JSON.parseObject(JSON.toJSONString(obj),LotteryRuleVo.class));
				xr.getObject().setId(obj.getId());
			}
			LOGGER.info("查询单个实体----->LotteryRule");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	@Override
	public XaResult<List<LotteryRuleVo>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<LotteryRule> page = lotteryRuleRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), LotteryRule.class), pageable);
		XaResult<List<LotteryRuleVo>> xr = new XaResult<List<LotteryRuleVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), LotteryRuleVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<List<LotteryRuleVo>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<LotteryRule> page = lotteryRuleRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), LotteryRule.class), pageable);
		XaResult<List<LotteryRuleVo>> xr = new XaResult<List<LotteryRuleVo>>();
		System.out.println(page.getContent().size());
		if(page.getContent().size() != 12){
			xr.error(XaConstant.Message.object_not_config);
			return xr;
		}else{
			xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), LotteryRuleVo.class));
			for(int i=0;i<page.getContent().size();i++){
				xr.getObject().get(i).setId(page.getContent().get(i).getId());
			}
		}
		return xr;
	}

	@Override
	public XaResult<LotteryRuleVo> multiOperate(String modelIds,
			Integer status) throws BusinessException {
		XaResult<LotteryRuleVo> xr = new XaResult<LotteryRuleVo>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				LotteryRule obj = lotteryRuleRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = lotteryRuleRepository.save(obj);
					xr.setObject(JSON.parseObject(JSON.toJSONString(obj), LotteryRuleVo.class));
					xr.getObject().setId(obj.getId());
				}
			}
		}
		LOGGER.info("更改数据状态----->LotteryRule");
		return xr;
	}

	@Override
	public XaResult<LotteryRuleVo> createModel(LotteryRule model)
			throws BusinessException {
		XaResult<LotteryRuleVo> xr = new XaResult<LotteryRuleVo>();
		LotteryRule obj = lotteryRuleRepository.save(model);
		xr.setObject(JSON.parseObject(JSON.toJSONString(obj), LotteryRuleVo.class));
		xr.getObject().setId(obj.getId());
		LOGGER.info("新增数据成功----->LotteryRule");
		return xr;
	}

	@Override
	public XaResult<LotteryRuleVo> updateModel(LotteryRule model)
			throws BusinessException {
		LotteryRule obj = lotteryRuleRepository.findOne(model.getId());
		XaResult<LotteryRuleVo> xr = new XaResult<LotteryRuleVo>();
		if (XaUtil.isNotEmpty(obj)) {
					obj.setMoney(XaUtil.isNotEmpty(model.getMoney()) ? model.getMoney() : obj.getMoney());
					obj.setMemo(XaUtil.isNotEmpty(model.getMemo()) ? model.getMemo() : obj.getMemo());
				obj = lotteryRuleRepository.save(obj);
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj), LotteryRuleVo.class));
			xr.getObject().setId(obj.getId());
		} else {
			xr.error(XaConstant.Message.object_not_find);
		}
		LOGGER.info("编辑数据成功----->LotteryRule");
		return xr;
	}

	/**
	 * 中奖逻辑处理
	 * @param userId
	 * @return
	 */
	@Override
	public XaResult<LotteryRuleVo> drawLottery(Long userId) throws BusinessException {
		XaResult<LotteryRuleVo> xr = new XaResult<>();
        XaResult<UserVo>  userXr = userService.findOne(userId);
		//1:计算是否能够中奖(中奖率)
		XaResult<ConfigurationTableVo> configResult = configurationTableService.findLastOne();
		if (configResult == null || configResult.getObject() == null) {
			xr.error(configResult.getMessage());
			return xr;
		}
		int rate = configResult.getObject().getSignin_winningRate();//中奖率,1-N的整数
		if (rate < 1) {
			xr.error("中奖率配置错误,1-N的正整数");
			return xr;
		}

        //每次抽奖获取的亲和币
        int consumeCon = configResult.getObject().getSignin_lottery_coin_per();
        //账号总钱数
        double countCoin = userXr.getObject().getBalanceCoin();
        if (countCoin < consumeCon) {
            xr.error("您的亲币不足,无法进行抽奖");
            return xr;
        }

		if (Identities.getBeanNumber(1, rate) != 1) {
			xr.setMessage("很遗憾没有中奖");
			//获取没有中奖的一规则对象
			LotteryRuleVo lotteryRuleVo = null;
			Pageable pageable = WebUitl.buildPageRequest(0, Integer.MAX_VALUE, "[{property:'createTime',direction:'DESC'}]");
			Map<String , Object> filterParams = filterParams = WebUitl.getParametersStartingWith("{'search_EQ_money':'" + 0 + "'}", "search_");
			XaResult<List<LotteryRuleVo>> xrr= findListNEStatusByFilter(XaConstant.Status.delete, filterParams, pageable);
			if (xrr == null || xrr.getObject().size() <= 0) {
				xr.error("没有配置未中奖设置");
				return xr;
			}
			lotteryRuleVo = xrr.getObject().get(Identities.getBeanNumber(0, xrr.getObject().size()-1));
            lotteryRuleVo.setLotteryTip(xr.getMessage());
			xr.setObject(lotteryRuleVo);
		} else {
			//中奖了
			//2:中奖能够选中的奖项
			//获取所有的中奖的奖项
			Pageable pageable = WebUitl.buildPageRequest(0, Integer.MAX_VALUE, "[{property:'createTime',direction:'DESC'}]");
			Map<String , Object> filterParams = filterParams = WebUitl.getParametersStartingWith("{'search_NE_money':'" + 0 + "'}", "search_");
			XaResult<List<LotteryRuleVo>> xrrr = findListNEStatusByFilter(XaConstant.Status.delete, filterParams, pageable);
			if (xrrr == null || xrrr.getObject().size() <= 0) {
				xr.error("没有配置中奖设置");
				return xr;
			}
			LotteryRuleVo lotteryRuleVo = xrrr.getObject().get(Identities.getBeanNumber(0, xrrr.getObject().size()-1));
			xr.setObject(lotteryRuleVo);
            lotteryRuleVo.setLotteryTip("恭喜你命中 " + lotteryRuleVo.getMoney() + " 亲币,奖励已经发放到你的亲币管理中");
		}

        //赚钱记录表新增一条记录(-300)抽奖花费的亲币
        XaResult<MakeMoneyTable> consumeXR = makeMoneyTableService.saveMakeMoneyRecord(userId, JConstant.ConsumeOrMakeMoney.Consume, consumeCon , JConstant.IntegralTypeEnum.LOTTERY.getIndex());

        //赚钱记录表新增一条记录(+10)(中奖的亲币)
        long makeMoney = xr.getObject().getMoney();
        XaResult<MakeMoneyTable> makeMoneyXR = makeMoneyTableService.saveMakeMoneyRecord(userId, JConstant.ConsumeOrMakeMoney.MakeMoney, (int) makeMoney , JConstant.IntegralTypeEnum.LOTTERY.getIndex());

        //赚钱记录表新增一条记录(+10)(转盘抽奖任务)
        double lotteryTaskMoney = configResult.getObject().getIncome_expenses_lottery_task_coin();
        XaResult<MakeMoneyTable> makeMoney_LotteryTaskXR = makeMoneyTableService.saveMakeMoneyRecord(userId, JConstant.ConsumeOrMakeMoney.MakeMoney, (int) lotteryTaskMoney , JConstant.IntegralTypeEnum.TASK.getIndex());

        xr.getObject().setUserVo(userService.findOne(userId).getObject());

		return xr;
	}
}
